package com.example.todoapp.http.controllers;

import com.example.todoapp.data.TagRepository;
import com.example.todoapp.data.entities.Tag;
import com.example.todoapp.http.ResponseStruct;
import com.example.todoapp.http.TagRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@RestController
public class TagController {

    @Autowired
    TagRepository tagRepository;

    // 获取所有标签
    @GetMapping("/tags")
    public ResponseStruct list() {
        List<Tag> tags = tagRepository.findAll();
        return ResponseStruct.wrap(tags);
    }

    // 获取单个标签
    @GetMapping("/tag/{id}")
    public ResponseStruct show(@PathVariable long id) {
        Tag tag = tagRepository.findFirstById(id);

        if (tag == null) {
            HashMap<String, Object> data = new HashMap<>();
            data.put("id", id);
            return new ResponseStruct(-1, "tag not found", data);
        }

        return ResponseStruct.wrap(tag);
    }

    // 新增标签
    @PostMapping("/tag")
    public ResponseStruct store(@RequestBody TagRequest request) {
        Tag tag = new Tag();
        BeanUtils.copyProperties(request, tag);
        tag.setCreatedAt(LocalDateTime.now());
        tag.setUpdatedAt(LocalDateTime.now());

        tagRepository.save(tag);

        return ResponseStruct.wrap(tag);
    }

    // 更新标签
    @PostMapping("/tag/{id}")
    public ResponseStruct update(@RequestBody TagRequest request, @PathVariable long id) {
        Tag tag = tagRepository.findFirstById(id);

        if (tag == null) {
            HashMap<String, Object> data = new HashMap<>();
            data.put("id", id);
            return new ResponseStruct(-1, "tag not found", data);
        }

        if (request.getName() != null) {
            tag.setName(request.getName());
        }
        if (request.getDescription() != null) {
            tag.setDescription(request.getDescription());
        }
        tag.setUpdatedAt(LocalDateTime.now());

        tagRepository.save(tag);

        return ResponseStruct.wrap(tag);
    }

    // 删除标签（如果需要）
    @PostMapping("/tag/delete/{id}")
    public ResponseStruct delete(@PathVariable long id) {
        Tag tag = tagRepository.findFirstById(id);

        if (tag == null) {
            HashMap<String, Object> data = new HashMap<>();
            data.put("id", id);
            return new ResponseStruct(-1, "tag not found", data);
        }

        tagRepository.delete(tag);

        return ResponseStruct.wrap(data -> data.put("id", id));
    }
}
